package com.beyond.pm.ui.login

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.beyond.common.constant.HOME_ROUTE
import com.beyond.common.manager.UserManager
import com.beyond.flow.collect.collectEvent
import com.beyond.pm.R
import com.beyond.pm.component.BaseEventComponent
import com.beyond.pm.component.EditFiled
import com.beyond.pm.component.MyIconButton
import com.beyond.pm.component.MyTopBar
import com.beyond.pm.component.MyTopBarStyle
import com.beyond.pm.component.state.TextFieldState
import com.beyond.pm.local.LocalNavController

/**
 * @author chen
 * @time 2023/5/31 13:34
 * @name ProjectManage
 * @class describe
 * UI上的输入数据使用remember获取
 * 业务逻辑处理的数据放在viewmodel 中通过 UiState 监听逻辑上的数据处理变化
 * UiEvent 是业务逻辑执行后的返回事件
 * UiIntent 是用户操作UI触发的事件
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun LoginScreen() {
    val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
    val nav = LocalNavController.current
    LaunchedEffect(Unit) {
        UserManager.clear()
    }
    Scaffold(
        modifier = Modifier
            .fillMaxSize(),
        topBar = {
            MyTopBar(
                style = MyTopBarStyle.Large,
                scrollBehavior = scrollBehavior,
                navigationIcon = {},
                title = { Text(text = stringResource(R.string.login)) },
                actions = {
                    if (nav.previousBackStackEntry != null)
                        MyIconButton(
                            onClick = { nav.popBackStack() },
                            imageVector = Icons.Default.Close,
                            contentDescription = stringResource(id = R.string.close)
                        )
                },
            )
        }
    )
    {
        LoginContent(it, scrollBehavior, nav)
    }

}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun LoginContent(
    paddingValues: PaddingValues,
    scrollBehavior: TopAppBarScrollBehavior,
    nav: NavHostController,
    viewModel: LoginViewModel = hiltViewModel()
) {
    BaseEventComponent(viewModel) {
        val lifecycleOwner = LocalLifecycleOwner.current
        LaunchedEffect(Unit) {
            viewModel.container.run {
//            uiStateFlow.collectState(lifecycleOwner) {
//                collectPartial(LoginUiState::loginStatus) {
//                    Log.e("====>", "loginStatus: $it")
//                }
//                collectPartial(LoginUiState::loadStatus) {
//                    isLoading.value = it
//                }
//            }
                uiEventFlow.collectEvent(lifecycleOwner) {
                    when (it) {
                        is LoginUiEvent.LoginSuccess -> {
                            nav.popBackStack()
                            nav.navigate(HOME_ROUTE)
                        }

//                    is LoginUiEvent.ErrorMessage -> {
//                        Log.e("====>", "ErrorMessage: ${it.message}")
//                        scope.launch {
//                            snackBarHostState.currentSnackbarData?.dismiss()
//                            snackBarHostState.showSnackbar(it.message)
//                        }
//                    }
                    }
                }
            }
        }

        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(
                    PaddingValues(
                        start = 16.dp,
                        top = paddingValues.calculateTopPadding(),
                        end = 16.dp,
                        bottom = paddingValues.calculateBottomPadding()
                    )
                )
                .nestedScroll(scrollBehavior.nestedScrollConnection),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            item {
                Spacer(modifier = Modifier.height(16.dp))
                Image(
                    painter = painterResource(id = R.mipmap.ic_launcher_round),
                    contentDescription = null,
                    modifier = Modifier.size(80.dp)
                )
                Spacer(modifier = Modifier.height(16.dp))
            }
            item { SignContent(viewModel) }
        }
    }
}


@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun SignContent(viewModel: LoginViewModel) {
    val keyboardController = LocalSoftwareKeyboardController.current
    Column(
        modifier = Modifier
            .fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        val passwordFocusRequest = remember { FocusRequester() }
        val userState =
            remember { TextFieldState(validator = { it.isNotEmpty() }).apply { text = "admin" } }
        EditFiled(
            label = stringResource(id = R.string.user_name),
            filedState = userState,
            keyboardType = KeyboardType.Text,
            onImeAction = { passwordFocusRequest.requestFocus() })
        Spacer(modifier = Modifier.height(16.dp))
        val passwordState = remember {
            TextFieldState(validator = { it.isNotEmpty() }).apply {
                text = "Thermofisher#0429"
            }
        }
        EditFiled(
            isPwd = true,
            label = stringResource(id = R.string.pwd),
            filedState = passwordState,
            imeAction = ImeAction.Done,
            modifier = Modifier.focusRequester(passwordFocusRequest),
            onImeAction = { keyboardController?.hide() }
        )
        Spacer(modifier = Modifier.height(16.dp))
        Button(
            onClick = {
                keyboardController?.hide()
                viewModel.dispatch(LoginUiIntent.Login(userState.text, passwordState.text))
            },
            modifier = Modifier.fillMaxWidth(),
            enabled = userState.isValid &&
                    passwordState.isValid
        ) {
            Text(text = stringResource(id = R.string.login))
        }
        Spacer(modifier = Modifier.height(16.dp))
        TextButton(
            onClick = {
                keyboardController?.hide()
            },
            modifier = Modifier.fillMaxWidth()
        ) {
            Text(text = stringResource(id = R.string.forgot_password))
        }
    }
}


// https://www.geeksforgeeks.org/android-jetpack-compose-encrypted-shared-preferences/
